package com.dolawing.phonecallapp.listenphonecall;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;

public class PhoneReceiver extends BroadcastReceiver {
    private Context mContext;
    private String TAG = PhoneReceiver.class.getName();
    private boolean dialFlag = false;
    private boolean incomingFlag = false;

    PhoneStateListener listener=new PhoneStateListener(){
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            //注意，方法必须写在super方法后面，否则incomingNumber无法获取到值。
            super.onCallStateChanged(state, incomingNumber);
            switch(state){
                case TelephonyManager.CALL_STATE_IDLE:
                    Log.i(TAG,"挂断");
                    dialFlag = false;
                    incomingFlag = false;
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    if (dialFlag==true){
                        Log.i(TAG,"去电，拨打电话");
                    } else if (incomingFlag==true){
                        Log.i(TAG,"来电，接听电话");
                    }else{
                        dialFlag = false;
                        incomingFlag = false;
                    }
                    break;
                case TelephonyManager.CALL_STATE_RINGING:
                    incomingFlag = true;  //来电话
                    Log.i(TAG,"响铃:来电号码"+incomingNumber);
                    //输出来电号码
                    break;
            }
        }
    };
    @Override
    public void onReceive(Context context, Intent intent) {
        mContext = context;
        Log.i("收到电话广播:{}", intent == null ? "null" : intent.getAction());
        //去电
        if(intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)){
            String phoneNumber = intent
                    .getStringExtra(Intent.EXTRA_PHONE_NUMBER);
            dialFlag = true;  //拨打电话
            Log.d("拨打电话", "call OUT:" + phoneNumber);
        }else{ // 来电
            TelephonyManager tm = (TelephonyManager)mContext.getSystemService(Service.TELEPHONY_SERVICE);
            if(tm != null){
                tm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
            }
        }

    }

}
